package com.ruoyi.common.utils.aes;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * @Description
 * @Author Admin小闫
 * @Date 2024/12/30
 */
@Component
public class AESEncryptor {

    private static final String ALGORITHM = "AES";

    private final SecretKey secretKey;

    public AESEncryptor(@Value("${aes.key}") String encodedKey) throws Exception {
        // 将配置文件中的base64编码的密钥解码成字节数组
        byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
        // 使用字节数组创建SecretKeySpec对象
        this.secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);
    }

    /**
     * 使用AES算法加密数据
     *
     * @param data 要加密的数据
     * @return 加密后的数据
     * @throws Exception 如果加密过程中发生错误
     */
    public String encrypt(String data)  {
        byte[] encryptedBytes = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encryptedBytes = cipher.doFinal(data.getBytes());
        } catch (Exception e) {
            throw new ServiceException("密码加密失败！"+e.getMessage());
        }
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 使用AES算法解密数据
     *
     * @param encryptedData 要解密的数据
     * @return 解密后的数据
     * @throws Exception 如果解密过程中发生错误
     */
    public String decrypt(String encryptedData){
        byte[] decryptedBytes = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            decryptedBytes = cipher.doFinal(decodedBytes);
        } catch (Exception e) {
            throw new ServiceException("密码解密失败！"+e.getMessage());
        }
        return new String(decryptedBytes);
    }
}